package com.net.core.intercept;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.net.core.intercept.wrapper.RequestWrapper;
import com.net.core.intercept.wrapper.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;


@Component
@Slf4j
@ConditionalOnProperty(value = "yxconfig.secretKey")
public class SecurityFilter implements Filter {

    @Value("${yxconfig.secretKey:}")
    private String secretKey;

    private AES aes;

    @Bean
    public AES getAes() {
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        secretKey = key.toString();
        System.out.println(secretKey);
        aes = SecureUtil.aes(key);
        return aes;
    }


    /**
     * 解密
     * @return
     * @param data
     */
    public String decode(String data) throws UnsupportedEncodingException {
        String decryptStr = aes.decryptStr(data, CharsetUtil.CHARSET_UTF_8);
        return decryptStr;
    }


    /**
     * 加密
     * @return
     * @param data
     */
    public String encode(byte[] data)  {
        String encryptHex = aes.encryptHex(data);
        return encryptHex;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String url = ((HttpServletRequest) request).getRequestURL().toString();
        if (UrlList.noSecurity(url)) {
            chain.doFilter(request, response);
            return;
        }
        String requestBody = getRequestBody((HttpServletRequest) request);
//        String temp = encode(requestBody);
//        String requestBodyMw = decode(temp);
        String requestBodyMw = decode(requestBody);
        response.setCharacterEncoding("UTF-8");
        log.info("入参解密数据："+requestBodyMw);
        RequestWrapper wrapRequest = new RequestWrapper( (HttpServletRequest) request, requestBodyMw);
        ResponseWrapper wrapResponse = new ResponseWrapper((HttpServletResponse) response);
        chain.doFilter(wrapRequest, wrapResponse);
        byte[] data = wrapResponse.getResponseData();

        String responseBodyMw = encode(data);

        log.info("出参加密数据："+responseBodyMw);
        writeResponse(response, responseBodyMw);
    }


    private String getRequestBody(HttpServletRequest req) {
        try {
            BufferedReader reader = req.getReader();
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String json = sb.toString();
            return json;
        } catch (IOException e) {
            log.info("请求体读取失败"+e.getMessage());
        }
        return "";
    }

    private void writeResponse(ServletResponse response, String responseString)
            throws IOException {
        PrintWriter out = response.getWriter();
        out.print(responseString);
        out.flush();
        out.close();
    }
}
